package com.mooc.lib_video.ui.live

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.mooc.ijk.widget.IJKView
import com.mooc.lib_network.entity.ApiConst
import com.mooc.lib_video.R
import com.mooc.lib_video.adapter.LiveCommentAdapter
import com.mooc.lib_video.im.WebSocketService
import com.mooc.lib_video.im.callback.MsgCallBack
import com.mooc.lib_video.im.model.MsgEntity
import com.mooc.lib_video.im.model.SVGEntity
import com.mooc.lib_video.im.model.TextEntity
import com.mooc.lib_video.ui.svga.SVGAFragment
import com.opensource.svgaplayer.*
import com.opensource.svgaplayer.SVGAParser.ParseCompletion
import com.opensource.svgaplayer.SVGASoundManager.init
import com.opensource.svgaplayer.utils.log.SVGALogger
import com.opensource.svgaplayer.utils.log.SVGALogger.setLogEnabled
import com.tb.emoji.Emoji
import com.tb.emoji.EmojiUtil
import com.tb.emoji.FaceFragment
import okhttp3.*
import java.io.File
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.*

class LiveActivity:AppCompatActivity(),
        View.OnClickListener, FaceFragment.OnEmojiClickListener,
        SVGAFragment.OnSVGAClickListener,MsgCallBack {

    private lateinit var live_bottom_frame: FrameLayout
    private lateinit var live_comment_edt : EditText
    private lateinit var live_player_view : IJKView
    private lateinit var live_msg_rv : RecyclerView
    private lateinit var live_svga_img : SVGAImageView
    private lateinit var webSocketService : WebSocketService
    private lateinit var adapter : LiveCommentAdapter
    private val handler = SvgHandler(this)
    //礼物动画处理->礼物容器保存全部礼物->播放一条礼物数据->移除一条礼物数据
    //礼物动画播放完成再次去礼物容器中获取直到礼物容器中数据为空
    private val svgList : LinkedList<SVGEntity> = LinkedList()
    private val thread:SVGThread=SVGThread()
    private var animFlag = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live)
        startWebSocketService()
        //开启SVGA框架LOG日志
        SVGALogger.setLogEnabled(true)
        //初始化SVGAParse
        SVGAParser.Companion.shareParser().init(this)
        initView()
        thread.start()
    }

    private fun initView(){
        findViewById<Button>(R.id.live_emoji_btn).setOnClickListener(this)
        findViewById<Button>(R.id.live_send_btn).setOnClickListener(this)
        findViewById<Button>(R.id.live_svg_btn).setOnClickListener(this)
        findViewById<ImageView>(R.id.live_back_img).setOnClickListener(this)
        live_bottom_frame = findViewById(R.id.live_bottom_frame)
        live_comment_edt = findViewById(R.id.live_comment_edt)
        live_player_view = findViewById(R.id.live_player_view)
        live_msg_rv = findViewById(R.id.live_msg_rv)
        var manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        live_msg_rv.layoutManager = manager
        adapter = LiveCommentAdapter()
        live_msg_rv.adapter = adapter
        live_svga_img = findViewById(R.id.live_svga_img)
        //设置svga动画循环1次
        live_svga_img.loops = 1
        //设置svga动画播放监听，播放完成移除动画
        live_svga_img.callback = object : SVGACallback{
            override fun onPause() {
            }

            override fun onFinished() {
                live_svga_img.clear()
                animFlag = true
//                live_svga_img.isAnimating
            }

            override fun onRepeat() {
            }

            override fun onStep(frame: Int, percentage: Double) {
            }

        }
    }

    override fun onResume() {
        super.onResume()
        live_bottom_frame.visibility = View.GONE
        live_player_view.setPath(ApiConst.LIVEURL)
        live_player_view.startVideo()
    }

    override fun onClick(v: View?) {

        when(v!!.id){
            R.id.live_back_img -> {
                finish()
            }
            R.id.live_send_btn -> {
                if (TextUtils.isEmpty(live_comment_edt.text)){
                    ToastUtils.showShort("请输入评论内容")
                    return
                }
                live_bottom_frame.visibility = View.GONE
                val entity = TextEntity()
                entity.type = 0
                entity.content = live_comment_edt.text.toString()
                sendMsg(entity)
            }
            R.id.live_svg_btn -> {
                live_bottom_frame.visibility = View.VISIBLE
                supportFragmentManager.beginTransaction().replace(
                        R.id.live_bottom_frame,
                        SVGAFragment()
                ).commit()
            }
            R.id.live_emoji_btn -> {
                live_bottom_frame.visibility = View.VISIBLE
                supportFragmentManager.beginTransaction().replace(
                        R.id.live_bottom_frame,
                        FaceFragment.Instance()
                ).commit()
            }
        }

    }

    override fun onEmojiDelete() {
        val text: String = live_comment_edt.getText().toString()
        if (text.isEmpty()) {
            return
        }
        if ("]" == text.substring(text.length - 1, text.length)) {
            val index = text.lastIndexOf("[")
            if (index == -1) {
                val action = KeyEvent.ACTION_DOWN
                val code = KeyEvent.KEYCODE_DEL
                val event = KeyEvent(action, code)
                live_comment_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event)
                try {
                    EmojiUtil.handlerEmojiText(
                            live_comment_edt,
                            live_comment_edt.getText().toString(),
                            this
                    )
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                return
            }
            live_comment_edt.getText().delete(index, text.length)
            try {
                EmojiUtil.handlerEmojiText(live_comment_edt, live_comment_edt.getText().toString(), this)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return
        }
        val action = KeyEvent.ACTION_DOWN
        val code = KeyEvent.KEYCODE_DEL
        val event = KeyEvent(action, code)
        live_comment_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event)
        try {
            EmojiUtil.handlerEmojiText(live_comment_edt,
                    live_comment_edt.getText().toString(), this)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onEmojiClick(emoji: Emoji?) {
        if (emoji != null) {
            val index: Int = live_comment_edt.getSelectionStart()
            val editable: Editable = live_comment_edt.getEditableText()
            if (index < 0) {
                editable.append(emoji.content)
            } else {
                editable.insert(index, emoji.content)
            }
            try {
                EmojiUtil.handlerEmojiText(live_comment_edt,
                        live_comment_edt.getText().toString(), this)
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    override fun onSvgAClick(name: String) {
        //封装发送动画消息发送到服务器
        val svgEntity = SVGEntity()
        svgEntity.type = 1
        svgEntity.name = "angel.svga"
        sendMsg(svgEntity)
        live_bottom_frame.visibility = View.GONE
    }

    private fun loadAnimation(name: String) {
        SVGAParser.Companion.shareParser().decodeFromAssets(name, object : ParseCompletion {
            override fun onComplete(videoItem: SVGAVideoEntity) {
                live_svga_img.setVideoItem(videoItem)
                animFlag = false
                live_svga_img.startAnimation()
            }

            override fun onError() {
            }
        },null)
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
        thread.interrupt()//中断线程->不会停止线程->改变Thread->interrupted()返回值
    }

    //播放礼物动画方法
    fun playSVG(){
        //判断当前是否具有正在播放得动画->
        if (!animFlag)
            return
        //获取最顶部数据
        var svgEntity = svgList.pop()
        //动画未在播放->播放动画
        loadAnimation(svgEntity!!.name!!)
    }

    //启动websocket 服务
    private fun startWebSocketService(){
        val intent = Intent(this,WebSocketService::class.java)
        bindService(intent,connection, BIND_AUTO_CREATE)
    }

    //发送聊天或礼物消息
    private fun sendMsg(msgEntity : MsgEntity){
        val body = RequestBody.create(MediaType.parse("application/json"),
                Gson().toJson(msgEntity))
        val request = Request.Builder().url(ApiConst.SENDMSGURL).post(body).build()
        //由于当前okhttp使用enqueue异步请求未使用同步请求，callback执行在子线程
        //execute()在当前线程发起请求
        OkHttpClient.Builder().build().newCall(request)
                .enqueue(object : Callback{
                    override fun onFailure(call: Call, e: IOException) {
                        //请求出错
                        Log.e("ZXY","send->onFailure")
                    }

                    override fun onResponse(call: Call, response: Response) {
                        //请求成功获取相应内容
                        Log.e("ZXY","send->onResponse"+response.toString())
                        runOnUiThread(Runnable {
                            live_comment_edt.setText("")
                        })
                    }

                })
    }

    val connection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val bind : WebSocketService.WebSocketBinder = service as WebSocketService.WebSocketBinder
            this@LiveActivity.webSocketService = bind.getWebSocketService()
            this@LiveActivity.webSocketService.msgCallBack = this@LiveActivity
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    //接收到后台维护长连接服务得回调数据
    //添加到recyclerView中做聊天显示
    override fun msgCall(entity: MsgEntity) {
        runOnUiThread {
            if (entity.type == 0){
                var textEntity = entity as TextEntity
                adapter.addData(textEntity)
                //由于直播或IM聊天中显示效果都为最近发送消息在列表最底部展示
                //且列表默认永远展示最后一条数据->设置列表滚动到最后一条数据
                var manager : LinearLayoutManager = live_msg_rv.layoutManager as LinearLayoutManager
                manager.scrollToPosition(adapter.data.size-1)
            }else{
                var svgEntity : SVGEntity = entity as SVGEntity
                svgList.add(svgEntity)
            }
        }

    }

    //轮询礼物容器线程->当礼物线程中具有数据时进行礼物动画播放
    inner class SVGThread : Thread() {
        override fun run() {
            super.run()
            while (!interrupted()){
                Thread.sleep(1000)
                if (svgList.size == 0)
                    continue//结束本次循环
                //切换线程到主线程获取一条礼物消息进行播放
                handler.sendEmptyMessage(100)
            }
        }
    }

}
class SvgHandler(act: LiveActivity) : Handler() {

    private var liveWeak : WeakReference<LiveActivity>
    init {
        liveWeak = WeakReference(act)
    }

    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        if (liveWeak.get()==null)
            return
        liveWeak.get()!!.playSVG()
    }

}
